//
//  WEXEmoticonPageCollectionViewCell.swift
//  microBlog
//
//  Created by apple on 16/4/28.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit

class WEXEmoticonPageCollectionViewCell: UICollectionViewCell {
    
    // MARK: - 供外部传入参数的属性
    var emoticons: [WEXEmoticonModel]? {
        
        didSet{
            
            guard let e = emoticons else{
                return
            }
            
            // 先隐藏所有按钮，防止cell复用的时候显示
            for value in Buttons {
                
                value.hidden = true
            }
            
            for (index,emoticon) in e.enumerate() {
                
//                print(emoticon)
                
                let button = Buttons[index]
                
                
                
                button.hidden = false
                
                button.emoticon = emoticon
                
            }
        }
        
        
    }
    
    var indexPath: NSIndexPath? {
        
        didSet{
            
            self.messageLabel.hidden = indexPath?.section != 0
            
            
        }
    }
    
    
    // MARK: - 存放按钮的数组
    private lazy var Buttons: [WEXEmoticonButton] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        backgroundColor = UIColor.clearColor()
        
//        添加按钮
        addChildButton()
        
//        添加文本信息
        contentView.addSubview(messageLabel)
        
//        添加删除按钮
        contentView.addSubview(deleteButton)
        
//        添加文本信息的约束
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView.snp_bottom).offset(-10)
            
        }
        
        let longPress: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress:")
        
        contentView.addGestureRecognizer(longPress)
        
    }

    
    // 添加按钮，给cell
    private func addChildButton(){
        
        for _ in 0..<WEXEmoticonKeyBoardEmoticonCount {
            
            let button = WEXEmoticonButton()
            
//            按钮添加点击事件
            button.addTarget(self, action: "emoticonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
            
            contentView.addSubview(button)
            
            Buttons.append(button)
        }
        
    }
    
    // 设置按钮的位置
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let itemW = self.frame.size.width / CGFloat(WEXEmoticonKeyBoardMaxCol)
        let itemH = (self.frame.size.height - 25) / CGFloat(WEXEmoticonKeyBoardMaxRow)
        
        
        for (index,button) in Buttons.enumerate() {
            
            let colIndex = index % WEXEmoticonKeyBoardMaxCol
            let rowIndew = index / WEXEmoticonKeyBoardMaxCol
            
            let x = itemW * CGFloat(colIndex)
            let y = itemH * CGFloat(rowIndew)
            
            button.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
        }
        
        let deleteButtonX = self.frame.size.width - itemW
        let deleteButtonY = self.frame.size.height - 25 - itemH
        
        deleteButton.frame = CGRect(x: deleteButtonX, y: deleteButtonY, width: itemW, height: itemH)
    }
    // MARK: - 响应点击事件
    
    // 长按按钮触发的事件
    @objc private func longPress(longPress: UILongPressGestureRecognizer){
        
//        取到手指点击的位置
        let location = longPress.locationInView(longPress.view)
        
//        取到按钮所在的点
        func buttonWithLocation(location: CGPoint) -> WEXEmoticonButton? {
            
            for value in Buttons {
                
                if CGRectContainsPoint(value.frame, location){
                    
                    return value
                }
            }
            
            return nil
            
        }
//        当当前点击按钮在按钮的范围内
        guard let button = buttonWithLocation(location) else{
            
            popView.removeFromSuperview()
            return
        }
        
        switch longPress.state {
            
        case .Began,.Changed:
            
            if popView.btn_emoticon.emoticon == button.emoticon {
                
                return
            }
//            取到最上层窗口
            let window = UIApplication.sharedApplication().windows.last!
//            转换坐标系，将button当前坐标系转换到最上层窗口坐标系中
            let rect = button.superview!.convertRect(button.frame, toView: window)
            
            popView.center.x = CGRectGetMidX(rect)
            
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
//            给popView中的按钮内容赋值
            popView.btn_emoticon.emoticon = button.emoticon
            
            window.addSubview(popView)
            
        default:
            popView.btn_emoticon.emoticon = nil
            popView.removeFromSuperview()
        }
        
        
    }
    
    // 删除按钮的触发事件
    @objc private func deleteButtonClick(){
        
        NSNotificationCenter.defaultCenter().postNotificationName(WEXEmoticonDeleteButtonNotification, object: nil)
    }
    
    // 点击表情按钮的触发事件
    @objc private func emoticonClick(button: WEXEmoticonButton){
        
//        保存最近添加的表情
        WEXEmoticonKeyBoardViewModel.sharedViewModel.saveRecentEmoticon(button.emoticon!)
        
//        表情按钮点击的通知
        NSNotificationCenter.defaultCenter().postNotificationName(WEXEmoticonButtonClickNotification, object: nil, userInfo: ["emoticon": button.emoticon!])
        
        // ------------attention----------------
        // nib中的图层结构注意
        // ------------attention----------------
        
//        获取最上层界面
        let window = UIApplication.sharedApplication().windows.last!
        
//        初始化一个popView
        let pop = WEXEmoticonPopView.popView()
        
//        坐标转换，将button的坐标转换到窗口上
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
//        pop的x中心和按钮在父控件中的x中心相同
        pop.center.x = CGRectGetMidX(rect)
//        pop的y值等于按钮的底部减去pop的高度
        pop.frame.origin.y = CGRectGetMaxY(rect) - pop.frame.height
        
        pop.btn_emoticon.emoticon = button.emoticon
        
//        print(button.emoticon)
        
        window.addSubview(pop)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            pop.removeFromSuperview()
        }

        
        
    }
    
    // MARK: - 懒加载子控件
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        return button
    }()
    
    // 最近使用的表情的标签
    private lazy var messageLabel: UILabel = {
       
        let message = UILabel(textColor: UIColor.darkGrayColor(), textFont: 12)
        
        message.text = "最近使用的表情"
        
        return message
        
    }()
    
    // 长按出现的popView
    private lazy var popView: WEXEmoticonPopView = {
       
        let pop = WEXEmoticonPopView.popView()
        
        return pop
        
    }()
    
}
